package com.bruce.apkinstaller.other;

import com.htrip.entitymodule.appUpdate.Apps;

import java.util.List;

/**
 * Created by Administrator on 2018/1/11.
 */

public class AppInstallImpl {
    private static AppInstallImpl mInstance;
    private InstallCallback mInstallCallback;
    private List<Apps> mApklist;
    private int finishedCount = 0;

    private AppInstallImpl() {
    }

    public static AppInstallImpl getInstance() {
        if (mInstance == null) {
            mInstance = new AppInstallImpl();
        }
        return mInstance;
    }

    public void setInstallCallback(List<Apps> apklist, InstallCallback installCallback) {
        mInstallCallback = installCallback;
        mApklist = apklist;
        startInstall(mApklist.get(0).getStoragePosition());
    }

    public void startInstall(final String apkfile) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if ((boolean) AppInstallUtils.install(apkfile)) {
                    finishedCount++;
                    intallNext();
                    mInstallCallback.success(mApklist.get(finishedCount));
                } else {
                    mInstallCallback.failure(mApklist.get(finishedCount), AppInstallUtils.install(apkfile));
                    intallNext();
                }
            }
        }).start();
    }

    private void intallNext() {
        if (finishedCount <= mApklist.size() - 1) {
            startInstall(mApklist.get(finishedCount).getStoragePosition());
        } else {
            finishedCount = 0;
        }
    }
}
